import React, {useEffect, useState} from 'react'
import {connectComponent} from '../../../store/utils'
import {bindErrorActions, ErrorActionsType} from '../../../store/action/error'
import {CONSTANTS} from '../../../../constants'
import {apiPost} from '../../../api'
import {LSKeys, LSMethods} from '../../../storage'
import {AuthActionsType, bindAuthActions} from '../../../store/action/auth'
import {formatToUI} from '../../../utils/date'
import {Loading} from '../../../ui/loading/Loading'
import {Button} from '../../../ui/button/Button'
import {round} from '../../../utils'
import {IOrderInfo} from '../../../../api/IOrderInfo'
import {CartDto} from '../../../../api/CartDto'
import Divider from '../../../ui/common/Divider'

export interface OrderInfoContainerProps {
  orderId: string
  cart: CartDto
  authActions: AuthActionsType
  errorActions: ErrorActionsType
}

const OrderInfoContainer: React.FC<OrderInfoContainerProps> = ({
  orderId,
  cart,
  authActions,
  errorActions,
}): React.ReactElement => {
  const [order, setOrder] = useState<IOrderInfo>(undefined)

  const loadHistory = async (): Promise<void> => {
    const token = LSMethods.getStorageData(LSKeys.TOKEN)
    const url = CONSTANTS.apiUrl + '/order/read'
    const res = await apiPost(url, {token: token, id: orderId}, {})
    const loadedOrder: IOrderInfo = res.result
    setOrder({...loadedOrder})
  }

  useEffect(() => {
    loadHistory()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const editOrder = async (): Promise<void> => {
    const token = LSMethods.getStorageData(LSKeys.TOKEN)
    const url = CONSTANTS.apiUrl + '/order/edit'
    const res = await apiPost(url, {token: token, id: orderId}, {})
    if (res.success) {
      authActions.setState({
        cart: {
          dishes: res.result.dishes,
          id: res.result.id,
        } as CartDto,
      })
      window.location.replace(CONSTANTS.webUrl + '/cart')
    }
  }

  const renderOrderDishes = (): React.ReactNode => {
    let items: React.ReactNode[] = []

    for (const item of order.dishes || []) {
      items.push(
        <div key={item.id} className={'order-item-list-item'}>
          <img
            className={'order-item-list-item-img'}
            src={item.img ? `${CONSTANTS.apiUrl}/image/${item.id}` : '/buffet/img/bg_img.jpg'}
            alt={'Изображение блюда'}
          />
          <div className={'order-item-list-item-body'}>
            <div className={'d-flex flex-column'}>
              <p className={'order-item-list-item-name'}>{item.dishname}</p>
              <p className={'order-item-list-item-description'}>цена {item.price} &#8381; / 1 шт</p>
            </div>
            <div className={'d-flex flex-row align-items-center justify-content-between'}>
              <div className={'d-flex flex-row align-items-center'}>
                <span className={'text-fs-16-24'}>Количество: {item.count}</span>
              </div>
              <span className={'order-item-list-item-price'}>
                {round(item.price * item.count)} &#8381;
              </span>
            </div>
          </div>
        </div>,
      )
    }

    return <div className={'order-item-list'}>{items}</div>
  }

  if (!order) {
    return <Loading />
  }

  return (
    <div className={'order-info-wrapper'}>
      <h1 className={'order-info-header'}>Заказа от {formatToUI(order.date)}</h1>
      {renderOrderDishes()}
      <Divider className={'w-100 mb-x4 mt-x2'} />
      <div className={'d-flex flex-row justify-content-between mb-x4'}>
        <span className={'text-fs-16-24'}>Итого: </span>
        <span className={'order-price-total'}>{round(order.sum)} &#8381;</span>
      </div>
      {order.is_editable && (
        <Button
          type={'button'}
          onClick={async (): Promise<void> => {
            await editOrder()
          }}
          size={'md'}
          className={'mb-0'}>
          Редактировать
        </Button>
      )}
    </div>
  )
}

export default connectComponent(
  (state, props) => ({
    orderId: props.match.params.orderId,
    user: state.auth.user,
    cart: state.auth.cart,
  }),
  (dispatch) => ({
    authActions: bindAuthActions(dispatch),
    errorActions: bindErrorActions(dispatch),
  }),
  OrderInfoContainer,
)
